# -*- coding:UTF-8 -*-
from django.http import JsonResponse, HttpResponse
import json, time, random, ast
from .models import *
from users.models import *
from datetime import datetime
from django.contrib.auth.decorators import login_required
from utils.json_schema import *
from utils.json_validate import json_validate
from notifications.signals import notify
from api.views import *



# 创建订单
@login_required()
@json_validate(create_work_schema)
def create_work(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 合同编号
    agreement_code = req_data["agreement_code"]
    # 品牌名称
    brand_name = req_data["brand_name"]
    # 完成时间
    finished_date = req_data["finished_date"]
    #联系人
    contact_name = req_data["contact_name"]
    # 联系电话
    contact_phone = req_data["contact_phone"]
    # 地址
    area = req_data["area"]
    # 订单类型 批量或自主 1为批量 2为自主
    type = req_data["type"]
    # 客户名称
    name = req_data["name"]
    # 订单下商品总数
    total = req_data["total"]
    data_dict = {}
    work = Work()
    # 判断订单是否已经分配好所属人
    if "owner" in req_data.keys() and req_data["owner"] != None:
        user_id = req_data["owner"]
        try:
            user = Users.objects.get(id=user_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "查询公司账户失败！"}}
            return JsonResponse(data)
        if not user.is_company:
            data = {"success": False, "data": {"msg": "此账户不是公司账户，不能进行分配！"}}
            return JsonResponse(data)
        work.owner = user
        # 返回所属公司名称
        data_dict["owner"] = work.owner.name

    # 判断订单是否有备注
    if "remark" in req_data.keys():
        work.remark = req_data["remark"]
        data_dict["remark"] = work.remark
    # 自动生成订单号
    time_code = int(time.time())
    if type == 1:
        passcode = 'DL'+str(time_code)+str(random.randint(1000, 9999))
    else:
        passcode = 'DZ-DL'+str(time_code)+str(random.randint(1000, 9999))
    work.passcode = passcode
    data_dict["passcode"] = work.passcode
    # 订单下商品数量
    work.total = total
    data_dict["total"] = work.total
    # 订单类型
    work.type = type
    data_dict["type"] = work.type
    # 下订单的商家名称
    work.name = name
    data_dict["name"] = work.name
    # 合同编号
    work.agreement_code = agreement_code
    data_dict["agreement_code"] = work.agreement_code
    # 品牌名称
    work.brand_name = brand_name
    data_dict["brand_name"] = work.brand_name
    # 完成时间
    work.finished_date = finished_date
    data_dict["finished_date"] = work.finished_date
    # 联系人
    work.contact_name = contact_name
    data_dict["contact_name"] = work.contact_name
    # 联系电话
    work.contact_phone = contact_phone
    data_dict["contact_phone"] = work.contact_phone
    # 地址
    work.area = area
    data_dict["area"] = work.area
    # 创建人
    work.create_user = request.user.name
    work.create_date = datetime.now()
    work.save()
    data = {"success": True, "data": {"msg": "录入新订单成功！", "data": data_dict}}
    return JsonResponse(data)


# 查询商品码
@login_required()
def get_goods_code(request):
    if request.method == 'POST':
        work_passcode = request.POST.get('passcode')
        if not work_passcode:
            data = {"success": False, "data": {"msg": "请输入订单号！"}}
            return JsonResponse(data)
        try:
            work = Work.objects.get(passcode=work_passcode)
        except Exception as e:
            data = {"success": False, "data": {"msg": "查询订单出错！"}}
            return JsonResponse(data)
        goods = Goods.objects.filter(work=work).values("code")
        data_list = [data for data in goods]
        data = {"success": True, "data": {"msg": "查询商品码成功！", "data": data_list}}
        return JsonResponse(data)


# 生成商品
@login_required()
@json_validate(create_books_schema)
def create_books(request):
    if request.method == "POST":
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        work_passcode = req_data["passcode"]
        query_list = []
        data_list = []
        # 根据work_id查询订单
        try:
            work = Work.objects.get(passcode=work_passcode)
        except Exception as e:
            data = {"success": False, "data": {"msg": "查询订单失败！"}}
            return JsonResponse(data)
        goods = Goods.objects.filter(work=work).values("code", "name")
        if goods.exists():
            data_list = [data for data in goods]
            data = {"success": True, "data": {"msg": "查询商品码成功！", "data": data_list}}
            return JsonResponse(data)
        else:
            # 获取订单商品总数
            total = int(work.total)
            # 生成商品条形码
            time_code = int(time.time())
            for num in range(total):
                # 判断是否是定制款
                if work.type == 1:
                    code = str(time_code)+'N'+str(total)+'-'+str(num+1)
                elif work.type == 2:
                    code = str(time_code)+'NDZ'+str(total)+'-'+str(num+1)
                else:
                    data = {"success": False, "data": {"msg": "Shooting type is wrong！"}}
                    return JsonResponse(data)
                try:
                    Goods.objects.get(code=code)
                    data = {"success": False, "data": {"msg": "商品编号应为唯一不重复的字符串！"}}
                    return JsonResponse(data)
                except Exception as e:
                    data_dict = {}
                    book = Goods()
                    book.code = code
                    book.name = work.brand_name
                    book.work = work
                    data_dict["code"] = code
                    data_dict["name"] = work.brand_name
                    data_dict["work"] = book.work.passcode
                    data_list.append(data_dict)
                    query_list.append(book)
            Goods.objects.bulk_create(query_list)
            data = {"success": True, "data": {"msg": "生成商品条形码成功！", "data": data_list}}
            return JsonResponse(data)


# 将订单添加上所属子公司
@login_required()
def create_owner(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # data是一个列表，列表元素为字典格式的数据，
    # eg:{"data":[{"passcode":DL12132132,"user_id":"1"},{"passcode":DL12147498732,"user_id":"2"}]}
    contents = req_data["data"]
    data_list = []
    for content in contents:
        data_dict = {}
        try:
            work = Work.objects.get(passcode=content["passcode"])
        except Exception as e:
            data = {"success": False, "data": {"msg": "此订单%s查询失败！" % content["passcode"]}}
            return JsonResponse(data)
        if work.owner:
            data = {"success": False, "data": {"msg": "此订单%s已经有所属公司！" % content["passcode"]}}
            return JsonResponse(data)
        # 查询公司账户
        try:
            user = Users.objects.get(id=content['user_id'])
        except Exception as e:
            data = {"success": False, "data": {"msg": "无此加盟店！"}}
            return JsonResponse(data)
        if user.is_company == 0:
            data = {"success": False, "data": {"msg": "此账户不是公司账户，无法添加所属订单！"}}
            return JsonResponse(data)
        work.owner = user
        # work.save()
        # 将商品码和对应所属公司信息发送给拍摄系统
        # 获取所属公司的username
        username = "admin"

        # 获取订单对应的商品码
        codes = work.bookOfWork.all().values("code")
        if len(codes) == 0:
            data = {"success": False, "data": {"msg": "此订单无对应商品码，请创建商品码后重试！"}}
            return JsonResponse(data)

        code_list = [code for code in codes]
        # 将商品码变成列表格式
        orders = []
        for code in code_list:
            orders.append(code["code"])
        #获取订单编号
        passcode = content["passcode"]
        import pdb
        pdb.set_trace()
        try:
            response = send_orders(username, orders, passcode)
        except Exception as e:
            data = {"success": False, "data": {"msg": "拍摄系统对接失败"}}
            return JsonResponse(data)
        if response.status_code == 200:
            work.save()
            data_dict["passcode"] = work.passcode
            data_dict["name"] = work.name
            data_dict["owner"] = work.owner.name
            data_list.append(data_dict)
        else:
            response_str = response.content.decode("utf8")
            # try:
            #     response_dict = ast.literal_eval(response_str)
            # except Exception as e:
            #     data = {"success": False, "data": {"msg": "访问拍摄系统返回数据错误！"}}
            #     return JsonResponse(data)
            # error = response_dict["error"]
            # error = str(response.content)
            # data_error = {"success": False, "data": {"msg": "拍摄系统接收数据失败！"}}
            data_error = {"success": False, "data": {"msg": "拍摄系统接收数据失败！", "error": str(response.content)}}
            return JsonResponse(data_error)
    data = {"success": True, "data": {"msg": "分配订单成功！", "data": data_list}}
    return JsonResponse(data)


# 创建任务（书）
@login_required()
# @json_validate(create_tasks_schema)
def create_tasks(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    query_list = []
    history_list = []
    data_list = []
    content_list = req_data["data"]
    for content in content_list:
        # 任务分为图片和视频两种  所以创建两个任务
        for stage_type in range(1, 3):
            data_dict = {}
            task = Task()
            # 根据code找到对应的图书并关联
            code = content["code"]
            try:
                book = Goods.objects.get(code=code)
            except Exception as e:
                data = {"success": False, "data": {"msg": "查询商品错误或商品不存在，请重试！"}}
                return JsonResponse(data)
            # 获取stage
            try:
                stage = StageName.objects.get(id=1)
            except Exception as e:
                data = {"success": False, "data": {"msg": "任务创建出错请重新创建!"}}
                return JsonResponse(data)
            user = request.user
            task.code = book
            task.diedline = content["diedline"]
            # 任务类型  1为平面   2为视频
            task.stage_type = stage_type
            task.stage = stage
            task.state = 4
            task.next_stage = 2
            task.create_user = user.name
            task.save()
            query_list.append(task)
            # 创建历史数据
            history = History()
            history.book = book
            history.task = task
            history.stage = task.stage
            history.user = user
            history.start_time = datetime.now()
            history_list.append(history)
            data_dict["code"] = book.code
            data_dict["diedline"] = content["diedline"]
            data_dict["stage"] = stage.name
            data_dict["stage_type"] = stage_type
            data_dict["state"] = 4
            data_dict["next_stage"] = 2
            data_dict["create_user"] = user.name
            data_list.append(data_dict)
    # Task.objects.bulk_create(query_list)
    # django1.4版本后加入了批量创建  减少查询次数  在此进行优化  代码如下
    History.objects.bulk_create(history_list)
    data = {"success": True, "data": {"msg": "录入任务完成!", "data": data_list}}
    return JsonResponse(data)


# 查询未完成的订单
@login_required()
def get_undone_work(request):
    if request.method =='GET':
        works = Work.objects.exclude(state=2)
        data_list = []
        for work in works:
            data_dict = {}
            data_dict["name"] = work.name
            data_dict["type"] = work.type
            data_dict["state"] = work.state
            data_dict["create_user"] = work.create_user
            data_dict["create_date"] = work.create_date
            if work.remark:
                data_dict["remark"] = work.remark
            if work.template:
                data_dict["template"] = work.template
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)
    else:
        data = {"success": False, "data": {"msg": "This API needs to use 'GET' method!"}}
        return JsonResponse(data)


# 查询订单
@login_required()
def get_works(request):
    if request.method == 'POST':
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        # TODO:时间范围查询
        for key in list(req_data.keys()):
            if not req_data.get(key):
                del req_data[key]
        if "finished_date" in req_data.keys():
            req_data["finished_date__range"] = list(req_data.pop("finished_date"))

        if "create_date" in req_data.keys():
            req_data["create_date__range"] = list(req_data.pop("create_date"))

        data_query = Work.objects.filter(**req_data).values()
        data_list = [data for data in data_query]
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)


# 查询任务
@login_required()
def get_task(request):
    if request.method == 'POST':
        # 任务对应的商品编号
        goods_code = request.POST.get("goods_code")
        # 任务对应的订单编号
        work_code = request.POST.get("work_code")
        # 订单的买家名称
        work_name = request.POST.get("work_name")
        # 任务进行到的阶段
        stage = request.POST.get("stage")
        # 任务创建的时间
        create_date = request.POST.get("create_date")
        search_dict = {}
        if goods_code:
            code = Goods.objects.get.filter(code=goods_code)
            search_dict["code"] = code
        if work_code:
            work = Work.objects.get.filter(passcode=work_code)
            goods = Goods.objects.get.filter(work=work)
            search_dict["code"] = goods
        if work_name:
            work = Work.objects.get.filter(name=work_name)
            goods = Goods.objects.get.filter(work=work)
            search_dict["code"] = goods
        if stage:
            search_dict["stage"] = stage
        if create_date:
            search_dict["create_date"] = create_date
        data_query = Task.objects.filter(**search_dict).values()
        data_list = [data for data in data_query]
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)


# 查询出待分配的任务
@login_required()
def get_undistribute_task(request):
    if request.method == 'GET':
        tasks = Task.objects.filter(state=1, stage__lt=5)
        data_list = []
        for task in tasks:
            data_dict = {}
            data_dict["id"] = task.id
            data_dict["code"] = task.code.code
            data_dict["work"] = task.code.work.name
            data_dict["stage"] = task.stage.name
            data_dict["state"] = task.state
            data_dict["diedline"] = task.diedline
            data_dict["create_date"] = task.create_date
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)


# 查询相对应阶段的涉及人员
@login_required()
def get_work_users(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    position = req_data["stage"]
    users = Users.objects.filter(position=position)
    data_list = []
    for user in users:
        data_dict = {}
        data_dict["id"] = user.id
        data_dict["name"] = user.name
        data_dict["position"] = user.position
        data_dict["task_counts"] = user.task.all().count()
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 分配任务
@login_required()
@json_validate(distribute_task_schema)
def distribute_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 需要分配的任务id列表
    task_list = req_data["task_list"]
    # 获取被分配任务的员工id
    user_id = req_data["user_id"]
    # 创建一个空列表 用于存储返回数据
    data_list = []
    # 根据id查询员工
    try:
        user = Users.objects.get(id=user_id)
    except Exception as e:
        data = {"success": False, "data": {"msg": "员工查询出错，请重试!"}}
        return JsonResponse(data)
    # 根据id查询任务
    for task_id in task_list:
        data_dict = {}
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "任务查询出错，请重试!"}}
            return JsonResponse(data)
        if task.stage.id == 5:
            continue
        if task.state != 1:
            continue
        # 任务分配完成 将任务的状态和阶段进行重新赋值
        task.state = 2
        task.save()
        # 调用add方法 添加多对多关系的外键数据
        user.task.add(task)
        # 创建历史数据
        history = History()
        history.book = task.code
        history.stage = task.stage
        history.start_time = datetime.now()
        history.user = user
        history.task = task
        history.save()
        # 发送系统通知
        notify.send(
            request.user,
            recipient=user,
            verb='分配了任务给你',
            target=task
        )
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["state"] = task.state
        data_dict["stage"] = task.stage.name
        data_dict["next_stage"] = task.next_stage
        name_list = []
        # 获取任务的全部人员 并进行遍历获取名字
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 查询该员工的任务
@login_required()
def get_user_task(request):
    if request.method == 'GET':
        data_list = []
        user = request.user
        tasks = user.task.all()
        for task in tasks:
            data_dict = {}
            data_dict["user"] = user.name
            data_dict["task_id"] = task.id
            data_dict["code"] = task.code.code
            data_dict["work"] = task.code.work.name
            data_dict["stage"] = task.stage.name
            data_dict["state"] = task.state
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)
    else:
        return HttpResponse("这个接口需要用GET方法访问！")


# 完成任务
@login_required()
@json_validate(finished_task_schema)
def finished_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    task_id = req_data["task_id"]
    user = request.user
    task_id_list = list(task.id for task in user.task.all())
    if task_id not in task_id_list:
        data = {"success": False, "data": {"msg": "所完成的任务不在此员工的任务列表中!"}}
        return JsonResponse(data)
    try:
        task = Task.objects.get(id=task_id)
    except Exception as e:
        data = {"success": False, "data": {"msg": "查询任务出错!"}}
        return JsonResponse(data)
    if task.state != 2:
        data = {"success": False, "data": {"msg": "此任务当前状态为%s，无法完成!" % task.state}}
        return JsonResponse(data)
    task.state = 3
    task.save()
    data_dict = {}
    data_dict["name"] = user.name
    data_dict["code"] = task.code.code
    data_dict["work"] = task.code.work.name
    data_dict["stage"] = task.stage.name
    data_dict["state"] = task.state
    data = {"success": True, "data": {"msg": "完成任务成功!", "data": data_dict}}
    return JsonResponse(data)


# 将任务提交到审核区
@login_required()
@json_validate(create_checking_task_schema)
def create_checking_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    task_list = req_data["task_list"]
    data_list = []
    for task_id in task_list:
        data_dict = {}
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "任务查询失败!"}}
            return JsonResponse(data)
        task.state = 4
        task.save()
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["work"] = task.code.work.name
        data_dict["stage"] = task.stage.name
        data_dict["state"] = task.state
        name_list = []
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "提交完成!", "data": data_list}}
    return JsonResponse(data)


# 查询待审核的任务
@login_required()
def get_checking_task(request):
    user = request.user
    position = user.position
    if position == 1:
        tasks = Task.objects.filter(stage=StageName.objects.get(id=position), state=4)
    elif position == 5:
        tasks = Task.objects.filter(stage_id__in=[4, 5], state=4)
    elif position == 2:
        data = {"success": True, "data": {"msg": "您无需审核!"}}
        return JsonResponse(data)
    else:
        stage_num = position-1
        stage = StageName.objects.get(id=stage_num)
        tasks = Task.objects.filter(stage=stage, state=4)
    data_list = []
    for task in tasks:
        data_dict = {}
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["work"] = task.code.work.name
        data_dict["stage"] = task.stage.name
        data_dict["state"] = task.state
        name_list = []
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 审核
@login_required()
@json_validate(check_task_schema)
def check_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 获取审核结果 1为通过审核 2为每通过
    check_flag = req_data["check_flag"]
    task_list = req_data["task_list"]
    for task_id in task_list:
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "查询任务失败!"}}
            return JsonResponse(data)
        if check_flag == 1:
            task.stage = StageName.objects.get(id=task.next_stage)
            if task.stage.id == 5:
                task.next_stage = 6
                task.state = 3
            if task.stage.id < 4:
                task.next_stage = task.stage.id + 1
                task.state = 1
            elif task.stage.id == 4:
                task.next_stage = task.stage.id + 1
                task.state = 4
            # 将任务的完成时间添加到历史数据
            try:
                history = task.historyOfTask.filter(stage=task.stage)
                for i in history:
                    i.finish_time = datetime.now()
                    i.save()
                    # 发送系统通知
                    notify.send(
                        request.user,
                        recipient=i.user,
                        verb='通过了你的审核',
                        target=task
                    )
            except Exception as e:
                data = {"success": False, "data": {"msg": "查询历史任务出错!"}}
                return JsonResponse(data)
            task.userOfTask.clear()
            task.save()
        elif check_flag == 2:
            task.state = 2
            try:
                reason = req_data["reason"]
            except Exception as e:
                data = {"success": False, "data": {"msg": "如审核不通过，请将原因填入!"}}
                return JsonResponse(data)
            task.save()
            # 将原因作为通知发送给用户
            notify.send(
                request.user,
                recipient=task.userOfTask,
                verb='未通过您的审核',
                target=task,
                description=reason
            )
        book = task.code
        if Task.objects.filter(code=book, stage__lt=6).count() == 0:
            book.finished = True
            book.save()
            work = book.work
            if work.bookOfWork.all().filter(finished=False).count() == 0:
                work.state = 3
    data = {"success": True, "data": {"msg": "操作成功!"}}
    return JsonResponse(data)


# 查询未归还图书
@login_required()
@json_validate(get_not_back_books_schema)
def get_not_back_books(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    work_name = req_data["work_name"]
    works = Work.objects.filter(name=work_name)
    data_list = []
    for work in works:
        books = work.bookOfWork.all().filter(finished=True, return_back=False)
        for book in books:
            data_dict = {}
            data_dict["code"] = book.code
            data_dict["name"] = book.name
            data_dict["work"] = book.work.name
            data_dict["create_date"] = book.create_date
            data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完毕!", "data": data_list}}
    return JsonResponse(data)


# 归还图书
@login_required()
def return_back_books(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    book_list = req_data["book_list"]
    data_list = []
    for book_id in book_list:
        data_dict = {}
        try:
            book = Goods.objects.get(id=book_id)
            book.return_back = True
            book.save()
            data_dict['name'] = book.name
            data_list.append(data_dict)
        except Exception as e:
            return HttpResponse("%s归还图书失败，请重试！" % book_id)
    data = {"success": True, "data": {"msg": "归还图书成功!", "data": data_list}}
    return JsonResponse(data)


# # 接受拍摄系统传参，将对应商品拍摄状态改为完成
# @json_validate(shooting_finished_schema)
# def shooting_finished(request):
#     json_str = request.body
#     json_str = json_str.decode()
#     req_data = json.loads(json_str)
#     code = req_data["code"]
#     try:
#         good = Goods.objects.get(code=code)
#     except Exception as e:
#         data = {"success": False, "data": {"msg": "此商品码无效!"}}
#         return JsonResponse(data)
#     good.shooting_status = True
#     good.is_active = False
#     good.save()
#     data = {"success": True, "data": {"msg": "拍摄完成!", "data": good.code}}
#     return JsonResponse(data)

# 理货
@login_required()
def manage_goods(request):
    if request.method == "POST":
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        codes = req_data["codes"]
        quantity = req_data["quantity"]
        remark = req_data["remark"]
        solution = req_data["solution"]
        query_list = []
        data_list = []

        for code in codes:
            try:
                good = Goods.objects.get(code=code)
            except Exception as e:
                data = {"success": False, "data": {"msg": "查询商品码失败！"}}
                return JsonResponse(data)
            data_dict = {}

            problem = Problem()
            problem.code = good
            data_dict["code"] = code

            problem.quantity = quantity
            data_dict["quantity"] = quantity

            problem.remark = remark
            data_dict["remark"] = remark

            problem.receiver = request.user
            data_dict["receiver"] = request.user.id

            problem.solution = solution
            data_dict["solution"] = solution

            # TODO:将图片地址存入数据库

            data_list.append(data_dict)
            query_list.append(problem)
            good.is_active = False
        Problem.objects.bulk_create(query_list)
        data = {"success": True, "data": {"msg": "创建成功！", "data": data_list}}
        return JsonResponse(data)


# 查询问题商品单
@login_required()
def get_problems(request):
    if request.method == "GET":
        user = request.user
        problems = Problem.objects.filter(receiver=user).values("code", "quantity", "remark", "solution")
        data_list = [data for data in problems]
        data = {"success": True, "data": {"msg": "查询理货单成功！", "data": data_list}}
        return JsonResponse(data)


# 接收图片
@login_required()
def receive_image(request):
    if request.method == "POST":
        base_path = "/opt/CRM/CRM/image"
        # {"key1":["value1","value2"], "key2":["value3","value4"]}
        file_dict = request.FILES.items()
        if not file_dict:
            data = {"success": False, "data": {"msg": "上传图片不能为空！"}}
            return JsonResponse(data)
        file_path_list = []
        for (k, v) in file_dict:
            file_data_list = request.FILES.getlist(k)
            for file_data in file_data_list:
                image_path = base_path + "/problem/" + file_data.name
                image = open(image_path, "wb")
                for chunk in file_data.chunks():
                    image.write(chunk)
                image.close()
                file_path_list.append(image_path)
        data = {"success": True, "data": {"msg": "上传图片成功！", "data": file_path_list}}
        return JsonResponse(data)


# 收退货
@login_required()
def create_logistics(request):
    if request.method == "POST":
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        try:
            work = Work.objects.get(passcode=req_data.pop("passcode"))
        except Exception as e:
            data = {"success": False, "data": {"msg": "此订单号不存在！"}}
            return JsonResponse(data)
        req_data["passcode"] = work
        for key in list(req_data.keys()):
            if not req_data[key]:
                del req_data[key]

        logistics = Logistics.objects.create(**req_data)

        data_dict = {}
        data_dict["passcode"] = logistics.passcode.passcode
        data_dict["id"] = logistics.id
        data_dict["receive_or_return"] = logistics.receive_or_return
        data_dict["user"] = logistics.user
        data_dict["contact"] = logistics.contact
        data_dict["date"] = logistics.date
        if data_dict["receive_or_return"] == 2:
            data_dict["style"] = logistics.style
            if data_dict["style"] == 1:
                data_dict["tracking_number"] = logistics.tracking_number
                data_dict["tracking_company"] = logistics.tracking_company
            elif data_dict["style"] == 2:
                data_dict["postman"] = logistics.postman
                data_dict["post_style"] = logistics.post_style

        data = {"success": True, "data": {"msg": "上传成功！", "data": data_dict}}
        return JsonResponse(data)


# 查询收退货单
@login_required()
def get_logistics(request):
    if request.method == "POST":
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        for key in list(req_data.keys()):
            if not req_data[key]:
                del req_data[key]
        logistics = Logistics.objects.filter(**req_data).values()

        data_list = [data for data in logistics]
        for data in data_list:
            if data:
                work = Work.objects.get(id=data["passcode_id"])
                data["passcode"] = work.passcode
                del data["passcode_id"]
        data = {"success": True, "data": {"msg": "查询收退货单成功！", "data": data_list}}
        return JsonResponse(data)




